package com.kim.authorization.server.config.extend;

import com.kim.authorization.server.config.util.AuthProperties;
import com.kim.authorization.server.service.UserAccountService;
import com.kim.oauth.common.constants.Oauth2ExceptionEnum;
import com.kim.oauth.common.model.UserAccount;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Component;

/**
 * 注册直接颁发令牌鉴权
 * <p>
 * 考虑目前仅支持手机号鉴权，但后续注册得到扩展此鉴权类也将被扩展，
 * 所以不与手机号验证码鉴权合并
 * </p>
 */
@Component
@Slf4j
public class RegisterAuthenticator extends AbstractPrepareIntegrationAuthenticator {

    /**
     * 注册直接颁发令牌鉴权授权类型
     */
    private final static String AUTH_TYPE = "register";

    /**
     * 用户账户Service
     */
    private final UserAccountService userAccountService;

    public RegisterAuthenticator(UserAccountService userAccountService) {
        this.userAccountService = userAccountService;
    }

    /**
     * 根据手机号验证码方式进行认证
     * <p>认证前须判断手机号存在而后再进行验证码验证</p>
     *
     * @param entity 集成认证实体
     */
    @Override
    public UserAccount authenticate(IntegrationAuthenticationEntity entity) {
        // 手机号
        String phone = entity.getAuthParameter(AuthProperties.AUTH_PHONE);
        if (StringUtils.isEmpty(phone)) {
            throw new OAuth2Exception(Oauth2ExceptionEnum.PHONE_NULL.getMsg());
        }

        // 根据手机号查询用户
        UserAccount userAccount = userAccountService.selectByPhone(phone);
        if (null == userAccount) {
            throw new OAuth2Exception(Oauth2ExceptionEnum.USER_NOT_FOUND.getMsg());
        }
        // 集成认证中除用户名密码不进行密码查询与校验
        setEmptyPassword(userAccount);
        return userAccount;
    }

    /**
     * 手机号验证码方式
     * {@inheritDoc}
     */
    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        return AUTH_TYPE.equals(entity.getAuthType());
    }
}
